package com.smartstate.dataManagement.controller;


import com.smartstate.dataManagement.core.BaseController;
import com.smartstate.dataManagement.entity.User;
import com.smartstate.dataManagement.entity.UserVo;
import com.smartstate.dataManagement.eunm.CommonEunm;
import com.smartstate.dataManagement.service.UserService;
import com.smartstate.dataManagement.vo.ResultCode;
import com.smartstate.dataManagement.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
@Api(tags = "对外暴露的接口")
@Slf4j
public class APIController extends BaseController {

    @Resource
    private UserService userService;
    
    @PostMapping(value = "/token")
    @ApiOperation(value = "获取token接口")
    public ResultVO getToken(@RequestParam String username, @RequestParam String password, @RequestParam(required = false) String code, @RequestParam(required = false) String randomStr){
        UserVo token = userService.loginByPassword(username, password, code, randomStr);
        if(token!=null){
            return ResultVO.ok(token.getAccessToken(),"获取token成功");
        }
        return  ResultVO.fail(ResultCode.INVALID_TOKEN);
    }

    @PostMapping(value = "/login")
    @ApiOperation(value = "登录接口")
    public ResultVO webLogin(@RequestBody(required = false) User  user){
        if(null !=user && StringUtils.isNotBlank(user.getUserName()) && StringUtils.isNotBlank(user.getPassword())){
            UserVo token = userService.loginByPassword(user.getUserName(), user.getPassword(),user.getCode(),user.getRandomStr());
            if(null !=token && null != token.getAccessToken()){
                return ResultVO.ok(token);
            }
            if(null != token  &&  StringUtils.isBlank(token.getUsername())){
                return ResultVO.fail("此用户不存在");
            }
            if(null != token && StringUtils.isNotBlank(token.getStatus().toString())  &&  token.getStatus().toString().equals(CommonEunm.STATUS_OFF.getValue())){
                return  ResultVO.fail("该用户已经被禁用，不能进行登录");
            }
            return ResultVO.fail(ResultCode.USERNAME_ERROR.getMessage());
        }
        return  ResultVO.fail("参数缺失， 请输入参数");
    }
}
